home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!genesis.demon.co.uk
- From: Lawrence Kirby <fred@genesis.demon.co.uk>
- Newsgroups: comp.lang.c
- Subject: Re: Recursion
- Date: Wed, 10 Apr 96 11:54:12 GMT
- Organization: none
- Message-ID: <829137252snz@genesis.demon.co.uk>
- References: <31624BC2.70D2@sooner.net> <828548265snz@genesis.demon.co.uk> <4k10q0$m5d@linet06.li.net> <4k4n40$tbi@news.microsoft.com>
- Reply-To: fred@genesis.demon.co.uk
- X-NNTP-Posting-Host: genesis.demon.co.uk
- X-Newsreader: Demon Internet Simple News v1.27
- X-Mail2News-Path: genesis.demon.co.uk
-
- In article <4k4n40$tbi@news.microsoft.com>
- a-cnadc@microsoft.com "Dann Corbit" writes:
-
- >In article <4k10q0$m5d@linet06.li.net>, jeremy@newshost.li.net says...
- >>
- >>Lawrence Kirby (fred@genesis.demon.co.uk) wrote:
- >>
- >>: I think you've picked a bad example. You really need an extra argument in
- >>: this case to pass on a running accumulator. A more suitable problem would
- >>: be to write a recursive function that is passed an integer (unsigned is
- >>: easiest) and writes the character representation to stdout.
- >>Absolutely WRONG. The whole point of recursion is that you do not need a
- >>running accumulator. When written correctly, the return value of each
- >>recursive loop will be the correct accumulated value. ANyhow, here is a
- >>better version of what I already posted...
- >>
- >>#include <stdio.h>
- >>#include <stdlib.h>
- >>#include <string.h>
- >>#include <math.h>
- >>
- >>int convert(char *string)
- >> {
- >> int value;
- >> int len = strlen(string);
- >>
- >> if (string[0] == '\0')
- >> return(0);
- >> value = convert(string+1);
- >> value += ((string[0] - '0') * pow(10,len-1));
- >> return(value);
- >> }
- >>
- >>void main()
- >> {
- >> char *string = "1234";
- >>
- >> printf("%d\n",convert(string));
- >> }
- >
- >I have to agree, with Mr. Kirby that recursion is a most
- >inelegant way to do this. Here is another ugly recursive
- >solution. The elegant way is atoi(). Iterative is next
- >best. Recursive is downright silly. But we all have our
- >silly moments.
-
- I'm not saying that recursion is inelegant. I'm saying that the elegant
- way to solve this problem recursively is to use an accumulator. IMHO
- Bill's is the most elegant solution posted so far (and uses an accumuator),
- and not just because it is short. Elegance is one of recursion's great
- strengths (when it is done right), however its practicality (at least in C)
- is weaker.
-
- ...
-
- >void main( )
-
- There's no need to copy bad code! :-)
-
- --
- -----------------------------------------
- Lawrence Kirby | fred@genesis.demon.co.uk
- Wilts, England | 70734.126@compuserve.com
- -----------------------------------------
-